package com.xzp.yygh.hosp.receiver;

import com.xzp.yygh.hosp.service.ScheduleService;
import com.xzp.yygh.model.hosp.Schedule;
import com.xzp.yygh.rabbit.constant.MqConst;
import com.xzp.yygh.rabbit.service.RabbitService;
import com.xzp.yygh.vo.hosp.ScheduleOrderVo;
import com.xzp.yygh.vo.msm.MsmVo;
import com.xzp.yygh.vo.order.OrderMqVo;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import sun.plugin2.message.Message;

import java.io.IOException;
import java.nio.channels.Channel;

public class HospitalReceiver {
    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel) throws IOException {
        // 正常更新剩余号数信息
        if(null != orderMqVo.getAvailableNumber()) {
            System.out.println("生成订单");
            // 获取排班信息
            Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
            // 更新排班信息
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            scheduleService.update(schedule);
        }else{
            System.out.println("取消订单。。。。。。");
            // 取消订单 没有availablenum
            // 获取排班信息
            Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
            // 更新排班信息
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber() +1);
            schedule.setReservedNumber(orderMqVo.getReservedNumber() - 1);
            scheduleService.update(schedule);
        }
        //利用mq发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if (msmVo != null) {
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }



    }

    }
